/**
 * 专家咨询API路由
 */
import express, { type Request, type Response } from 'express';

const router = express.Router();

// 专家信息接口类型定义
interface Expert {
  id: string;
  name: string;
  avatar: string;
  title: string;
  hospital: string;
  department: string;
  specialties: string[];
  experience: number;
  rating: number;
  reviewCount: number;
  consultCount: number;
  price: number;
  isOnline: boolean;
  responseTime: string;
  introduction: string;
  education: string[];
  certifications: string[];
  availableTime: {
    start: string;
    end: string;
  }[];
  consultTypes: ('text' | 'voice' | 'video')[];
}

interface ConsultOrder {
  id: string;
  expertId: string;
  userId: string;
  type: 'text' | 'voice' | 'video';
  status: 'pending' | 'ongoing' | 'completed' | 'cancelled';
  duration: number; // 分钟
  price: number;
  title: string;
  description: string;
  createdAt: string;
  startTime?: string;
  endTime?: string;
  rating?: number;
  review?: string;
}

interface Message {
  id: string;
  orderId: string;
  senderId: string;
  senderType: 'user' | 'expert';
  type: 'text' | 'image' | 'voice' | 'system';
  content: string;
  duration?: number; // 语音消息时长
  timestamp: string;
  status: 'sending' | 'sent' | 'read';
}

// 模拟数据存储
let experts: Expert[] = [
  {
    id: '1',
    name: '张医生',
    avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20doctor%20portrait%20friendly%20smile&image_size=square',
    title: '主任医师',
    hospital: '北京儿童医院',
    department: '儿科',
    specialties: ['新生儿护理', '婴幼儿发育', '疫苗接种'],
    experience: 15,
    rating: 4.9,
    reviewCount: 1250,
    consultCount: 3200,
    price: 200,
    isOnline: true,
    responseTime: '5分钟内',
    introduction: '从事儿科临床工作15年，擅长新生儿护理、婴幼儿发育评估和疫苗接种指导。',
    education: ['北京大学医学部 临床医学博士', '哈佛大学 儿科进修'],
    certifications: ['执业医师证', '儿科专科医师证', '国际母乳喂养顾问'],
    availableTime: [
      { start: '09:00', end: '12:00' },
      { start: '14:00', end: '18:00' }
    ],
    consultTypes: ['text', 'voice', 'video']
  },
  {
    id: '2',
    name: '李护士长',
    avatar: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=professional%20nurse%20portrait%20caring%20smile&image_size=square',
    title: '护士长',
    hospital: '上海妇幼保健院',
    department: '新生儿科',
    specialties: ['母乳喂养', '新生儿护理', '产后康复'],
    experience: 12,
    rating: 4.8,
    reviewCount: 890,
    consultCount: 2100,
    price: 150,
    isOnline: false,
    responseTime: '10分钟内',
    introduction: '资深护士长，专注母乳喂养指导和新生儿护理，帮助数千家庭解决育儿难题。',
    education: ['复旦大学 护理学硕士'],
    certifications: ['护士执业证', '国际泌乳顾问', '新生儿护理专科证'],
    availableTime: [
      { start: '08:00', end: '16:00' }
    ],
    consultTypes: ['text', 'voice']
  }
];

let consultOrders: ConsultOrder[] = [];
let messages: Message[] = [];

/**
 * 获取专家列表
 * GET /api/expert/list
 */
router.get('/list', (req: Request, res: Response) => {
  try {
    const { 
      page = 1, 
      limit = 10, 
      specialty, 
      isOnline, 
      sortBy = 'rating' 
    } = req.query;
    
    let filteredExperts = [...experts];
    
    // 按专业筛选
    if (specialty) {
      filteredExperts = filteredExperts.filter(expert => 
        expert.specialties.includes(specialty as string)
      );
    }
    
    // 按在线状态筛选
    if (isOnline !== undefined) {
      filteredExperts = filteredExperts.filter(expert => 
        expert.isOnline === (isOnline === 'true')
      );
    }
    
    // 排序
    if (sortBy === 'rating') {
      filteredExperts.sort((a, b) => b.rating - a.rating);
    } else if (sortBy === 'price') {
      filteredExperts.sort((a, b) => a.price - b.price);
    } else if (sortBy === 'experience') {
      filteredExperts.sort((a, b) => b.experience - a.experience);
    }
    
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedExperts = filteredExperts.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedExperts,
        total: filteredExperts.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < filteredExperts.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取专家列表失败'
    });
  }
});

/**
 * 获取专家详情
 * GET /api/expert/:id
 */
router.get('/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const expert = experts.find(e => e.id === id);
    
    if (!expert) {
      return res.status(404).json({
        success: false,
        error: '专家不存在'
      });
    }
    
    res.json({
      success: true,
      data: expert
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取专家详情失败'
    });
  }
});

/**
 * 创建咨询订单
 * POST /api/expert/consult
 */
router.post('/consult', (req: Request, res: Response) => {
  try {
    const { 
      expertId, 
      userId, 
      type, 
      duration = 30, 
      title, 
      description 
    } = req.body;
    
    const expert = experts.find(e => e.id === expertId);
    if (!expert) {
      return res.status(404).json({
        success: false,
        error: '专家不存在'
      });
    }
    
    if (!expert.consultTypes.includes(type)) {
      return res.status(400).json({
        success: false,
        error: '专家不支持该咨询方式'
      });
    }
    
    const order: ConsultOrder = {
      id: Date.now().toString(),
      expertId,
      userId,
      type,
      status: 'pending',
      duration,
      price: expert.price,
      title,
      description,
      createdAt: new Date().toISOString()
    };
    
    consultOrders.push(order);
    
    res.status(201).json({
      success: true,
      data: order
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '创建咨询订单失败'
    });
  }
});

/**
 * 获取咨询订单列表
 * GET /api/expert/orders
 */
router.get('/orders', (req: Request, res: Response) => {
  try {
    const { userId, status, page = 1, limit = 10 } = req.query;
    
    let filteredOrders = [...consultOrders];
    
    if (userId) {
      filteredOrders = filteredOrders.filter(order => order.userId === userId);
    }
    
    if (status) {
      filteredOrders = filteredOrders.filter(order => order.status === status);
    }
    
    // 按创建时间倒序
    filteredOrders.sort((a, b) => 
      new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
    );
    
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedOrders = filteredOrders.slice(startIndex, endIndex);
    
    // 补充专家信息
    const ordersWithExpert = paginatedOrders.map(order => {
      const expert = experts.find(e => e.id === order.expertId);
      return {
        ...order,
        expert: expert ? {
          name: expert.name,
          avatar: expert.avatar,
          title: expert.title,
          hospital: expert.hospital
        } : null
      };
    });
    
    res.json({
      success: true,
      data: {
        list: ordersWithExpert,
        total: filteredOrders.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < filteredOrders.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取订单列表失败'
    });
  }
});

/**
 * 获取咨询订单详情
 * GET /api/expert/orders/:id
 */
router.get('/orders/:id', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const order = consultOrders.find(o => o.id === id);
    
    if (!order) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    const expert = experts.find(e => e.id === order.expertId);
    
    res.json({
      success: true,
      data: {
        ...order,
        expert
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取订单详情失败'
    });
  }
});

/**
 * 发送消息
 * POST /api/expert/messages
 */
router.post('/messages', (req: Request, res: Response) => {
  try {
    const { 
      orderId, 
      senderId, 
      senderType, 
      type, 
      content, 
      duration 
    } = req.body;
    
    const order = consultOrders.find(o => o.id === orderId);
    if (!order) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    const message: Message = {
      id: Date.now().toString(),
      orderId,
      senderId,
      senderType,
      type,
      content,
      duration,
      timestamp: new Date().toISOString(),
      status: 'sent'
    };
    
    messages.push(message);
    
    res.status(201).json({
      success: true,
      data: message
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '发送消息失败'
    });
  }
});

/**
 * 获取消息列表
 * GET /api/expert/messages/:orderId
 */
router.get('/messages/:orderId', (req: Request, res: Response) => {
  try {
    const { orderId } = req.params;
    const { page = 1, limit = 50 } = req.query;
    
    const orderMessages = messages
      .filter(m => m.orderId === orderId)
      .sort((a, b) => new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime());
    
    const startIndex = (Number(page) - 1) * Number(limit);
    const endIndex = startIndex + Number(limit);
    const paginatedMessages = orderMessages.slice(startIndex, endIndex);
    
    res.json({
      success: true,
      data: {
        list: paginatedMessages,
        total: orderMessages.length,
        page: Number(page),
        limit: Number(limit),
        hasMore: endIndex < orderMessages.length
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '获取消息列表失败'
    });
  }
});

/**
 * 评价专家
 * POST /api/expert/evaluate
 */
router.post('/evaluate', (req: Request, res: Response) => {
  try {
    const { orderId, rating, review, tags, anonymous = false } = req.body;
    
    const orderIndex = consultOrders.findIndex(o => o.id === orderId);
    if (orderIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    // 更新订单评价信息
    consultOrders[orderIndex].rating = rating;
    consultOrders[orderIndex].review = review;
    
    // 更新专家评分（简化计算）
    const expertId = consultOrders[orderIndex].expertId;
    const expertIndex = experts.findIndex(e => e.id === expertId);
    if (expertIndex !== -1) {
      const expert = experts[expertIndex];
      const newRating = ((expert.rating * expert.reviewCount) + rating) / (expert.reviewCount + 1);
      experts[expertIndex].rating = Math.round(newRating * 10) / 10;
      experts[expertIndex].reviewCount += 1;
    }
    
    res.json({
      success: true,
      message: '评价提交成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '提交评价失败'
    });
  }
});

/**
 * 更新订单状态
 * PUT /api/expert/orders/:id/status
 */
router.put('/orders/:id/status', (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    const orderIndex = consultOrders.findIndex(o => o.id === id);
    if (orderIndex === -1) {
      return res.status(404).json({
        success: false,
        error: '订单不存在'
      });
    }
    
    consultOrders[orderIndex].status = status;
    
    if (status === 'ongoing') {
      consultOrders[orderIndex].startTime = new Date().toISOString();
    } else if (status === 'completed') {
      consultOrders[orderIndex].endTime = new Date().toISOString();
    }
    
    res.json({
      success: true,
      data: consultOrders[orderIndex]
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      error: '更新订单状态失败'
    });
  }
});

export default router;